package com.thot.timyag.common;


import java.io.File;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.util.CollectionUtils;

/**
 * @author yangjf
 * @version 0.1.0
 * @time 2019/4/12
 */
public class CommonUtil {

    public static <T> Set<T> subSet(Set<T> objSet, int page, int size) {
        if (CollectionUtils.isEmpty(objSet)) {
            return Collections.emptySet();
        }
        List<T> objList = Lists.newArrayList(objSet);
        if (page == 0) {
            page = 1;
        }
        int fromIndex = Math.min((page - 1) * size, objList.size());
        int toIndex = Math.min(page * size, objList.size());
        return Sets.newLinkedHashSet(objList.subList(fromIndex, toIndex));
    }

    public static String getDefaultPath(String defaultPath) {
        File file = getBaseJarPath();
        if (null != file && file.exists() && file.isDirectory()) {
            File tempFile = new File(file.getAbsolutePath() + File.separator + defaultPath);
            if (!tempFile.exists()) {
                if (!tempFile.mkdirs()) {
                    throw new RuntimeException("创建临时目录失败");
                }
            }
            return tempFile.getAbsolutePath();
        } else {
            throw new RuntimeException("");
        }
    }


    public static File getBaseJarPath() {
        ApplicationHome home = new ApplicationHome(CommonUtil.class);
        File jarFile = home.getSource();
        return jarFile.getParentFile();
    }

    public static Object getFieldValue(Object obj, String fieldName) {
        try {
            Field field = obj.getClass().getDeclaredField(fieldName);
            boolean accessible = field.isAccessible();
            field.setAccessible(true);
            Object value = field.get(obj);
            field.setAccessible(accessible);
            return value;
        } catch (Exception e) {
            throw new RuntimeException("ERROR: 加载对象中[" + fieldName + "]", e);
        }
    }

}
